package com.demo.accessibilitykeeper;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;

import androidx.core.app.NotificationCompat;

/**
 * 前台服务
 * 用于保持应用在后台运行，防止被系统杀死
 */
public class ForegroundService extends Service {
    
    private static final String TAG = "ForegroundService";
    private static final String CHANNEL_ID = "foreground_service_channel";
    private static final int NOTIFICATION_ID = 1002;
    
    private Handler mainHandler;
    private Runnable keepAliveRunnable;
    private boolean isRunning = false;
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "ForegroundService onCreate");
        
        mainHandler = new Handler(Looper.getMainLooper());
        createNotificationChannel();
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "ForegroundService onStartCommand");
        
        if (!isRunning) {
            startForeground();
            startKeepAlive();
            isRunning = true;
        }
        
        // 返回START_STICKY确保服务被杀死后自动重启
        return START_STICKY;
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "ForegroundService onDestroy");
        
        stopKeepAlive();
        isRunning = false;
        
        // 尝试重启服务
        restartService();
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    /**
     * 创建通知渠道
     */
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                CHANNEL_ID,
                "系统辅助工具",
                NotificationManager.IMPORTANCE_DEFAULT
            );
            channel.setDescription("显示系统服务的运行状态");
            channel.setShowBadge(true);
            channel.enableLights(true);
            channel.enableVibration(false);
            
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
    }
    
    /**
     * 启动前台服务
     */
    private void startForeground() {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
            this, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
        );
        
        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("系统辅助工具")
            .setContentText("系统服务正在运行")
            .setSmallIcon(R.drawable.ic_notification)
            .setContentIntent(pendingIntent)
            .setOngoing(true)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setCategory(NotificationCompat.CATEGORY_SERVICE)
            .setAutoCancel(false)
            .build();
        
        startForeground(NOTIFICATION_ID, notification);
    }
    
    /**
     * 启动保活机制
     */
    private void startKeepAlive() {
        keepAliveRunnable = new Runnable() {
            @Override
            public void run() {
                if (isRunning) {
                    // 执行保活操作
                    performKeepAlive();
                    
                    // 20秒后再次执行
                    mainHandler.postDelayed(this, 20000);
                }
            }
        };
        
        mainHandler.post(keepAliveRunnable);
    }
    
    /**
     * 停止保活机制
     */
    private void stopKeepAlive() {
        if (keepAliveRunnable != null) {
            mainHandler.removeCallbacks(keepAliveRunnable);
            keepAliveRunnable = null;
        }
    }
    
    /**
     * 执行保活操作
     */
    private void performKeepAlive() {
        Log.d(TAG, "Performing foreground keep alive operations");
        
        // 更新通知
        updateNotification();
        
        // 检查无障碍服务状态
        checkAccessibilityService();
        
        // 启动保活服务
        startKeepAliveService();
    }
    
    /**
     * 更新通知
     */
    private void updateNotification() {
        String contentText = "系统服务运行中 | 服务已激活";
        
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
            this, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
        );
        
        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("系统辅助工具")
            .setContentText(contentText)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentIntent(pendingIntent)
            .setOngoing(true)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setCategory(NotificationCompat.CATEGORY_SERVICE)
            .setAutoCancel(false)
            .build();
        
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager != null) {
            notificationManager.notify(NOTIFICATION_ID, notification);
        }
    }
    
    /**
     * 检查无障碍服务状态
     */
    private void checkAccessibilityService() {
        // 检查无障碍服务是否正在运行
        if (!isAccessibilityServiceRunning()) {
            Log.w(TAG, "Accessibility service is not running, attempting to restart");
            restartAccessibilityService();
        }
    }
    
    /**
     * 检查无障碍服务是否运行
     */
    private boolean isAccessibilityServiceRunning() {
        // 这里可以添加更复杂的检查逻辑
        // 简单实现：检查服务是否在运行
        return true; // 简化实现
    }
    
    /**
     * 重启无障碍服务
     */
    private void restartAccessibilityService() {
        try {
            // 发送广播重启无障碍服务
            Intent intent = new Intent("com.demo.accessibilitykeeper.RESTART_ACCESSIBILITY_SERVICE");
            sendBroadcast(intent);
        } catch (Exception e) {
            Log.e(TAG, "Error restarting accessibility service", e);
        }
    }
    
    /**
     * 启动保活服务
     */
    private void startKeepAliveService() {
        try {
            Intent intent = new Intent(this, KeepAliveService.class);
            startService(intent);
        } catch (Exception e) {
            Log.e(TAG, "Error starting keep alive service", e);
        }
    }
    
    /**
     * 重启服务
     */
    private void restartService() {
        Log.d(TAG, "Restarting foreground service");
        
        // 延迟重启
        mainHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    Intent intent = new Intent(ForegroundService.this, ForegroundService.class);
                    startService(intent);
                } catch (Exception e) {
                    Log.e(TAG, "Error restarting foreground service", e);
                }
            }
        }, 3000);
    }
}
